package com.mysite.websocket.ws;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import com.alibaba.fastjson.JSONObject;
import com.mysite.websocket.service.UserService;
import com.mysite.websocket.util.JsonUtil;
import com.mysite.websocket.vo.UserVo;
import com.mysite.websocket.vo.WebsocketMessageType;
import com.mysite.websocket.vo.WebsocketMessageVo;

@Component
public class WebSocketHandler extends AbstractWebSocketHandler {

	@Autowired
	private UserService userService;

	private static final Map<UserVo, WebSocketSession> sessionMap = Collections
			.synchronizedMap(new HashMap<UserVo, WebSocketSession>());

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        UserVo user = (UserVo) session.getAttributes().get("CURRENT_USER");
		String msg = user.getRealname() + " Login !";
		TextMessage tm = new TextMessage(JsonUtil.toJson(new WebsocketMessageVo(WebsocketMessageType.TEXT_SYS, msg)));
		for (WebSocketSession s : sessionMap.values()) {
			s.sendMessage(tm);
		}
		sessionMap.put(user, session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        UserVo user = (UserVo) session.getAttributes().get("CURRENT_USER");
		sessionMap.remove(user);
		String msg = user.getRealname() + " Logout !";
		TextMessage tm = new TextMessage(JsonUtil.toJson(new WebsocketMessageVo(WebsocketMessageType.TEXT_SYS, msg)));
		for (WebSocketSession s : sessionMap.values()) {
			s.sendMessage(tm);
		}
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String payload = message.getPayload();
        System.err.println(payload);
        UserVo user = (UserVo) session.getAttributes().get("CURRENT_USER");
        WebsocketMessageVo messageVo = JSONObject.parseObject(payload, WebsocketMessageVo.class);
        messageVo.setSpeaker(user.getRealname());
		TextMessage tm = new TextMessage(JsonUtil.toJson(messageVo));
		for (WebSocketSession s : sessionMap.values()) {
			if (user.equals(s.getAttributes().get("CURRENT_USER"))) {
				continue;
			}
			s.sendMessage(tm);
		}
	}
}
